package com.aviccxzx.smarthome.ConfigModule;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.widget.ImageView;
import android.widget.TextView;

import com.aviccxzx.smarthome.DeviceModule.GosDeviceModuleBaseActivity;
import com.aviccxzx.smarthome.GosApplication;
import com.aviccxzx.smarthome.MsgID;
import com.aviccxzx.smarthome.R;
import com.aviccxzx.smarthome.UserModule.AddFailActivity;
import com.aviccxzx.smarthome.UserModule.AddGateSuccActivity;
import com.aviccxzx.smarthome.UserModule.SoftApActivity;
import com.aviccxzx.smarthome.netutil.app.App;
import com.aviccxzx.smarthome.view.RoundProgressBar;
import com.gizwits.gizwifisdk.api.GizDeviceSharing;
import com.gizwits.gizwifisdk.api.GizWifiDevice;
import com.gizwits.gizwifisdk.api.GizWifiSDK;
import com.gizwits.gizwifisdk.enumration.GizDeviceSharingWay;
import com.gizwits.gizwifisdk.enumration.GizWifiConfigureMode;
import com.gizwits.gizwifisdk.enumration.GizWifiErrorCode;
import com.gizwits.gizwifisdk.enumration.GizWifiGAgentType;
import com.gizwits.gizwifisdk.listener.GizDeviceSharingListener;
import com.gizwits.gizwifisdk.listener.GizWifiSDKListener;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

@SuppressLint("HandlerLeak")
public class GosAirlinkConfigCountdownActivity extends
        GosConfigModuleBaseActivity implements View.OnClickListener {

    /**
     * The tv Time
     */
    private TextView tvTimer;

    /**
     * The rpb Config
     */
    private RoundProgressBar rpbConfig;

    /**
     * 倒计时
     */
    int secondleft = 60;

    /**
     * The timer
     */
    Timer timer;

    /**
     * 配置用参数
     */
    String workSSID, workSSIDPsw;


    List<GizWifiGAgentType> modeList, modeDataList;


    ImageView radar_scan_img;
    Animation rotateAnim;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_gos_airlink_config_countdown);

        initView();
        initData();
        startAirlink();

    }

    Timer gatetimer;
    /*GizWifiDeviceListener scribledListener = new GizWifiDeviceListener() {
        @Override
        public void didSetSubscribe(GizWifiErrorCode result, final GizWifiDevice device, boolean isSubscribed) {
            super.didSetSubscribe(result, device, isSubscribed);
            if (result == GizWifiErrorCode.GIZ_SDK_SUCCESS) {
                gatetimer = new Timer();
                gatetimer.schedule(new TimerTask() {
                    int i = 30;

                    @Override
                    public void run() {
                        i--;
                        if (i != 0) {
                            if (device.isBind()) {
                                //绑定成功
                                Looper.prepare();
                                Message message = new Message();
                                message.what = handler_key.BIND.ordinal();
                                handler.sendMessage(message);
                                Looper.loop();
                            }
                        } else {
                            //绑定失败
                            Looper.prepare();
                            Message message = new Message();
                            message.what = handler_key.FAILED.ordinal();
                            handler.sendMessage(message);
                            Looper.loop();
                        }
                    }
                }, 0, 1000);

            } else {
                Message message = new Message();
                message.what = handler_key.FAILED.ordinal();
                handler.sendMessage(message);
            }
        }
    };*/


    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    String token = "";
    String uid = "";

    private void initView() {
        ((TextView) findViewById(R.id.title_tv)).setText("正在扫描");

        findViewById(R.id.ll_title_left_view).setOnClickListener(this);
        findViewById(R.id.islinking_cancle).setOnClickListener(this);
        radar_scan_img = (ImageView) findViewById(R.id.radar_scan_img);
        token = spf.getString("Token", "");
        uid = spf.getString("Uid", "");
    }

    private void initData() {
        workSSID = spf.getString("workSSID", "");
        workSSIDPsw = spf.getString("workSSIDPsw", "");
        modeDataList = new ArrayList<>();
        modeDataList.add(GizWifiGAgentType.GizGAgentESP);
        modeList = new ArrayList<>();

        modeList.add(modeDataList
                .get(GosAirlinkChooseDeviceWorkWiFiActivity.modeNum));

    }

    Timer mtimer = new Timer();

    private void startAirlink() {
        GizWifiSDK.sharedInstance().setDeviceOnboarding(workSSID, workSSIDPsw,
                GizWifiConfigureMode.GizWifiAirLink, null, 60, modeList);
        handler.sendEmptyMessage(handler_key.START_TIMER.ordinal());
        mtimer.schedule(new TimerTask() {
//            int i = 2;
            int i = 60;
            @Override
            public void run() {
                i--;
                if (i == 0) {
                    Looper.prepare();
                    Message message = new Message();
                    message.what = handler_key.FAILED.ordinal();
                    handler.sendMessage(message);
                    Looper.loop();
                }
            }
        }, 0, 1000);
    }

    public void softApLink(){
        Intent soft = new Intent(this,SoftApActivity.class);
        startActivity(soft);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ll_title_left_view:
                if (mtimer != null) {
                    mtimer.cancel();
                    mtimer = null;
                }
                if (gatetimer != null) {
                    gatetimer.cancel();
                    gatetimer = null;
                }
                if (bindTimer != null) {
                    bindTimer.cancel();
                    bindTimer = null;
                }
                finish();
                break;
            case R.id.islinking_cancle:
                if (mtimer != null) {
                    mtimer.cancel();
                    mtimer = null;
                }
                if (gatetimer != null) {
                    gatetimer.cancel();
                    gatetimer = null;
                }
                if (bindTimer != null) {
                    bindTimer.cancel();
                    bindTimer = null;
                }
                finish();
                break;
        }
    }

    private enum handler_key {

        /**
         * 倒计时提示
         */
        TIMER_TEXT,

        /**
         * 倒计时开始
         */
        START_TIMER,

        /**
         * 配置成功
         */
        SUCCESSFUL,

        /**
         * 配置失败
         */
        FAILED,
        /**
         * 配置失败
         */
        BIND_FAILED,
        /**
         * 配置失败
         */
        BIND,

    }

    GizWifiDevice GateDevice;
    /**
     * The handler.
     */
    Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            handler_key key = handler_key.values()[msg.what];
            switch (key) {
                case TIMER_TEXT:
                    break;
                case BIND:

                    if (mtimer != null) {
                        mtimer.cancel();
                        mtimer = null;
                    }
                    if (gatetimer != null) {
                        gatetimer.cancel();
                        gatetimer = null;
                    }
                    if (bindTimer != null) {
                        bindTimer.cancel();
                        bindTimer = null;
                    }
                    App.getApp().showToast("网关添加成功");
                    Intent succ = new Intent(GosAirlinkConfigCountdownActivity.this, AddGateSuccActivity.class);
                    startActivity(succ);
                    finish();
                    break;

                case START_TIMER:
                    setRotate();
                    break;

                case SUCCESSFUL:
                    GosDeviceModuleBaseActivity.deviceslist = GizWifiSDK.sharedInstance().getDeviceList();
                    for (int i = 0; i < GosDeviceModuleBaseActivity.deviceslist.size(); i++) {
                        if (GosDeviceModuleBaseActivity.deviceslist.get(i).getProductKey().equals(MsgID.PK_GATE) && GosDeviceModuleBaseActivity.deviceslist.get(i).getMacAddress().equals(GosApplication.GMac)) {
                            GateDevice = GosDeviceModuleBaseActivity.deviceslist.get(i);
                        }
                    }
                    if (GateDevice != null) {
                        if (GateDevice.isBind()) {
                            //绑定成功 分享
                            //强行分享 使其成为管理员、
                            // 设置设备分享监听
                            bindTimer = new Timer();
                            bindTimer.schedule(new TimerTask() {
                                int i = 15;

                                @Override
                                public void run() {
                                    i--;
                                    if (i == 0) {
                                        Looper.prepare();
                                        Message message = new Message();
                                        message.what = handler_key.FAILED.ordinal();
                                        handler.sendMessage(message);
                                        Looper.loop();
                                    } else if (!TextUtils.isEmpty(GateDevice.getDid())) {
                                        Looper.prepare();
                                        GizDeviceSharing.setListener(setRoleListener);
                                        // 在设备列表中找到可以分享的设备
                                        // 二维码分享设备
                                        GizDeviceSharing.sharingDevice(token, GateDevice.getDid(), GizDeviceSharingWay.GizDeviceSharingByQRCode, null, null);
                                        Looper.loop();
                                    }
                                }
                            }, 0, 1000);
                        } else {
                            //先绑定
                            //再分享
                            bindTimer = new Timer();
                            bindTimer.schedule(new TimerTask() {
                                int i = 15;

                                @Override
                                public void run() {
                                    i--;
                                    if (i == 0) {
                                        Looper.prepare();
                                        Message message = new Message();
                                        message.what = handler_key.FAILED.ordinal();
                                        handler.sendMessage(message);
                                        Looper.loop();
                                    } else if (!TextUtils.isEmpty(GateDevice.getDid())) {
                                        if (bindTimer != null) {
                                            bindTimer.cancel();
                                            bindTimer = null;
                                        }
                                        //先绑定
                                        //再分享
                                        GizWifiSDK.sharedInstance().setListener(sdkListener);
                                        GizWifiSDK.sharedInstance().bindRemoteDevice(uid, token, GateDevice.getMacAddress(), GateDevice.getProductKey(), MsgID.PS);
                                    }
                                }
                            }, 0, 1000);
                        }
                    } else {
                        Message message = new Message();
                        message.what = handler_key.FAILED.ordinal();
                        handler.sendMessage(message);
                    }
                    break;

                case FAILED:
                    if (mtimer != null) {
                        mtimer.cancel();
                        mtimer = null;
                    }
                    if (gatetimer != null) {
                        gatetimer.cancel();
                        gatetimer = null;
                    }
                    if (bindTimer != null) {
                        bindTimer.cancel();
                        bindTimer = null;
                    }
                    App.getApp().showToast("添加失败");
                    Intent fail = new Intent(GosAirlinkConfigCountdownActivity.this, AddFailActivity.class);
                    fail.putExtra("gateway", true);
                    startActivity(fail);
                    finish();
                    break;
                case BIND_FAILED:
                    if (mtimer != null) {
                        mtimer.cancel();
                        mtimer = null;
                    }
                    if (gatetimer != null) {
                        gatetimer.cancel();
                        gatetimer = null;
                    }
                    if (bindTimer != null) {
                        bindTimer.cancel();
                        bindTimer = null;
                    }
                    App.getApp().showToast("添加失败");
                    Intent bind_fail = new Intent(GosAirlinkConfigCountdownActivity.this, AddFailActivity.class);
                    bind_fail.putExtra("bind", true);
                    bind_fail.putExtra("gateway", true);
                    startActivity(bind_fail);
                    finish();
                    break;

                default:
                    break;

            }
        }
    };

    public static GizWifiDevice gatedevice = null;
    GizDeviceSharingListener setRoleListener = new GizDeviceSharingListener() {
        // 实现设备分享的回调
        @Override
        public void didSharingDevice(GizWifiErrorCode result, String deviceID, int sharingID, Bitmap QRCodeImage) {
            if (result == GizWifiErrorCode.GIZ_SDK_SUCCESS) {
                // 分享成功
                // 分享成功即可提示添加设备成功
                gatedevice = GateDevice;
                Message message = new Message();
                message.what = handler_key.BIND.ordinal();
                handler.sendMessage(message);
            } else if(result == GizWifiErrorCode.GIZ_OPENAPI_ONLY_OWNER_CAN_SHARE){
                if (GateDevice != null && !TextUtils.isEmpty(GateDevice.getDid())) {
                    GizWifiSDK.sharedInstance().setListener(sdkListener);
                    GizWifiSDK.sharedInstance().unbindDevice(uid, token, GateDevice.getDid());
                }
            }else {
                /*Message message = new Message();
                message.what = handler_key.FAILED.ordinal();
                handler.sendMessage(message);*/
                //TODO 上面临时注释 分享失败的时候再次分享
                Looper.prepare();
                GizDeviceSharing.setListener(setRoleListener);
                GizDeviceSharing.sharingDevice(token, GateDevice.getDid(), GizDeviceSharingWay.GizDeviceSharingByQRCode, null, null);
                Looper.loop();
            }
        }
    };
    Timer bindTimer = null;
    // 实现回调
    GizWifiSDKListener sdkListener = new GizWifiSDKListener() {
        @Override
        public void didUnbindDevice(GizWifiErrorCode result, String did) {
            if (result == GizWifiErrorCode.GIZ_SDK_SUCCESS) {
                // 解绑成功
                Message message = new Message();
                message.what = handler_key.BIND_FAILED.ordinal();
                handler.sendMessage(message);
            } else {
                // 解绑失败
                //再解绑网关
                if (GateDevice != null && !TextUtils.isEmpty(GateDevice.getDid())) {
                    GizWifiSDK.sharedInstance().setListener(sdkListener);
                    GizWifiSDK.sharedInstance().unbindDevice(uid, token, GateDevice.getDid());
                }
            }
        }

        @Override
        public void didBindDevice(GizWifiErrorCode result, String did) {
            if (result == GizWifiErrorCode.GIZ_SDK_SUCCESS) {
                //绑定成功 分享
                //强行分享 使其成为管理员、
                // 设置设备分享监听
                bindTimer = new Timer();
                bindTimer.schedule(new TimerTask() {
                    int i = 15;

                    @Override
                    public void run() {
                        i--;
                        if (i == 0) {
                            Looper.prepare();
                            Message message = new Message();
                            message.what = handler_key.FAILED.ordinal();
                            handler.sendMessage(message);
                            Looper.loop();
                        } else if (!TextUtils.isEmpty(GateDevice.getDid())) {
                            Looper.prepare();
                            GizDeviceSharing.setListener(setRoleListener);
                            GizDeviceSharing.sharingDevice(token, GateDevice.getDid(), GizDeviceSharingWay.GizDeviceSharingByQRCode, null, null);
                            Looper.loop();
                        }
                    }
                }, 0, 1000);
            } else if (result == GizWifiErrorCode.GIZ_OPENAPI_ONLY_OWNER_CAN_BIND) {
                // 分享失败
                //再解绑网关
                if (GateDevice != null && !TextUtils.isEmpty(GateDevice.getDid())) {
                    GizWifiSDK.sharedInstance().setListener(sdkListener);
                    GizWifiSDK.sharedInstance().unbindDevice(uid, token, GateDevice.getDid());
                }
            } else {
                // 绑定失败 提示添加设备失败

                /*Message message = new Message();
                message.what = handler_key.FAILED.ordinal();
                handler.sendMessage(message);*/
                //TODO 上面临时注掉 绑定失败时再次绑定
                GizWifiSDK.sharedInstance().setListener(sdkListener);
                GizWifiSDK.sharedInstance().bindRemoteDevice(uid, token, GateDevice.getMacAddress(), GateDevice.getProductKey(), MsgID.PS);
            }

        }
    };

    private void setRotate() {
        // 加载动画
        rotateAnim = AnimationUtils.loadAnimation(this, R.anim.radar_rotate);
        LinearInterpolator lin = new LinearInterpolator();// 匀速旋转
        rotateAnim.setInterpolator(lin);
        radar_scan_img.startAnimation(rotateAnim);
    }

    // 屏蔽掉返回键
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            quitAlert(this, timer);
            return true;
        }
        return false;
    }


    @Override
    protected void didSetDeviceOnboarding(GizWifiErrorCode result, String mac, String did, String productKey) {
        super.didSetDeviceOnboarding(result, mac, did, productKey);
        if (GizWifiErrorCode.GIZ_SDK_DEVICE_CONFIG_IS_RUNNING == result) {
            return;
        }
        if (timer != null) {
            timer.cancel();
        }
        Message message = new Message();
        if (result == GizWifiErrorCode.GIZ_SDK_SUCCESS) {
            message.what = handler_key.SUCCESSFUL.ordinal();
            GosApplication.GMac = mac;
            spf.edit().putString("GMac", mac).commit();
        } else {
            message.what = handler_key.FAILED.ordinal();
            message.obj = toastError(result);
        }
        Log.i("Apptest", result.toString());
        handler.sendMessage(message);
    }
}
